<template>
  <div class="login-container">
    <div class="backgound-svg">
      <LoginBackground></LoginBackground>
    </div>
    <div class="login-form-wrap">
      <div class="login-header">账号密码登录</div>
      <el-form :model="form" ref="ruleFormRef" :rules="rules" label-width="0px">
        <el-form-item prop="username" label="">
          <el-input type="text" name="username" placeholder="手机号/用户名/邮箱" v-model="form.username" />
        </el-form-item>
        <el-form-item prop="password" label="">
          <el-input type="password" name="password" placeholder="密码" v-model="form.password" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="!form.username || !form.password"
            @click="submitForm(ruleFormRef)"
            style="width: 100%"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import LoginBackground from '@/components/SvgIcon/LoginBackground.vue';
import {useRouter} from 'vue-router';
import {ROUTE_HOME} from '@/router/names';
import {useUserStore} from '@/stores/userStore';

const userStore = useUserStore();

const router = useRouter();

if (userStore.isAuthorized) {
  router.replace({name: ROUTE_HOME});
}

const form = reactive({
  username: userStore.username || '',
  password: ''
});

const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  username: [{required: true, message: '请输入用户名', trigger: ['blur', 'change', 'focus']}],
  password: [{required: true, message: '请输入密码', trigger: ['blur', 'change', 'focus']}]
});

// 1. 登录成功 保存用户名
// 2. 如果退出登录，那么显示上一次登录成功的用户名称
// 3. 如果已经登录，那么直接进入home页面

const submitForm = async (formEl: FormInstance | undefined) => {
  try {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
      if (valid) {
        console.log('submit!', form);
        // 通过接口返回登录成功
        router.replace({name: ROUTE_HOME});

        userStore.setUsername(form.username);
        userStore.setAuthorized('ok');
      } else {
        console.log('error submit!', fields);
      }
    });
  } catch (error) {
    console.log('[submitForm error]', error);
  }
};
</script>
<style lang="scss" scoped>
.login-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}
.login-form-wrap {
  width: 308px;
  // margin-top: 155px;
  position: relative;
  top: -10px;
  left: 100px;
}

.login-header {
  font-weight: 400;
  font-size: 14px;
  line-height: 22px;
  color: #303133;
  margin-bottom: 14px;
}

.backgound-svg {
  position: absolute;
}
</style>
